package com.summer.bilibili.validator.role;

import cn.hutool.core.util.ArrayUtil;
import com.summer.bilibili.util.SecurityUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 验证当前用户是否拥有@Role注解中指定的任意角色权限。
 */
public class RoleValidator implements ConstraintValidator < Role, Object > {
    private Role instance;

    @Override
    public void initialize ( Role constraintAnnotation ) {
        instance = constraintAnnotation;
    }

    @Override
    public boolean isValid ( Object value , ConstraintValidatorContext context ) {
        if ( value == null ) {
            return true;
        }
        // 忽略值检查
        if ( ArrayUtil.isNotEmpty ( instance.ignores ( ) ) ) {
            for ( String ignore : instance.ignores ( ) ) {
                if ( Objects.toString ( value ).equals ( ignore ) ) {
                    return true;
                }
            }
        }
        // 角色权限验证
        return SecurityUtils.hasAnyRole ( instance.value ( ) );
    }
}
